<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数学函数可视化工具</title>
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/function-plot@1.22.8/dist/function-plot.js"></script>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #1a2a6c, #b21f1f, #1a2a6c);
            color: #333;
            line-height: 1.6;
            padding: 20px;
            min-height: 100vh;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            overflow: hidden;
        }
        
        header {
            background: linear-gradient(90deg, #2c3e50, #1a237e);
            color: white;
            padding: 25px 30px;
            text-align: center;
        }
        
        h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }
        
        .subtitle {
            font-size: 1.1rem;
            opacity: 0.9;
        }
        
        .content {
            display: flex;
            flex-wrap: wrap;
            padding: 20px;
        }
        
        .controls {
            flex: 1;
            min-width: 300px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            margin-right: 20px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
        }
        
        .plot-area {
            flex: 2;
            min-width: 400px;
            background: white;
            border-radius: 10px;
            padding: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            min-height: 500px;
        }
        
        .section-title {
            font-size: 1.4rem;
            margin: 20px 0 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #3498db;
            color: #2c3e50;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
        }
        
        input, select {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        input:focus, select:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }
        
        .btn {
            background: linear-gradient(to right, #3498db, #1a237e);
            color: white;
            border: none;
            padding: 14px 20px;
            font-size: 18px;
            border-radius: 8px;
            cursor: pointer;
            width: 100%;
            font-weight: 600;
            letter-spacing: 1px;
            transition: all 0.3s ease;
            margin-top: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
            background: linear-gradient(to right, #2980b9, #161d6e);
        }
        
        .examples {
            background: #e3f2fd;
            border-left: 4px solid #3498db;
            padding: 15px;
            border-radius: 0 8px 8px 0;
            margin: 20px 0;
        }
        
        .examples h3 {
            color: #1a237e;
            margin-bottom: 10px;
        }
        
        .examples ul {
            padding-left: 20px;
        }
        
        .examples li {
            margin-bottom: 8px;
            color: #2c3e50;
        }
        
        #plot {
            width: 100%;
            height: 500px;
        }
        
        .function-type {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .function-type-btn {
            flex: 1;
            padding: 12px;
            background: #e0e0e0;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            text-align: center;
            transition: all 0.3s;
        }
        
        .function-type-btn.active {
            background: #3498db;
            color: white;
        }
        
        .function-inputs {
            display: none;
        }
        
        .function-inputs.active {
            display: block;
        }
        
        .footer {
            text-align: center;
            padding: 20px;
            color: #7f8c8d;
            font-size: 0.9rem;
            background: #f8f9fa;
            border-top: 1px solid #eee;
        }
        
        @media (max-width: 768px) {
            .content {
                flex-direction: column;
            }
            
            .controls {
                margin-right: 0;
                margin-bottom: 20px;
            }
            
            h1 {
                font-size: 2rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>数学函数可视化工具</h1>
            <p class="subtitle">使用function-plot.js绘制函数图像、导函数、切线与圆锥曲线</p>
        </header>
        
        <div class="content">
            <div class="controls">
                <h2 class="section-title">控制面板</h2>
                
                <div class="function-type">
                    <button class="function-type-btn active" data-type="function">函数图像</button>
                    <button class="function-type-btn" data-type="derivative">导函数</button>
                    <button class="function-type-btn" data-type="tangent">切线</button>
                    <button class="function-type-btn" data-type="conic">圆锥曲线</button>
                </div>
                
                <div class="function-inputs" id="function-inputs">
                    <div class="form-group">
                        <label for="function-expression">函数表达式 (f(x))</label>
                        <input type="text" id="function-expression" value="x^2" placeholder="例如: sin(x), x^2, log(x)">
                    </div>
                </div>
                
                <div class="function-inputs" id="derivative-inputs">
                    <div class="form-group">
                        <label for="derivative-expression">原函数表达式</label>
                        <input type="text" id="derivative-expression" value="x^3 - 2*x" placeholder="例如: x^3 - 2*x">
                    </div>
                </div>
                
                <div class="function-inputs" id="tangent-inputs">
                    <div class="form-group">
                        <label for="tangent-function">原函数表达式</label>
                        <input type="text" id="tangent-function" value="sin(x)" placeholder="例如: cos(x), e^x">
                    </div>
                    
                    <div class="form-group">
                        <label for="tangent-point">切点 x 坐标</label>
                        <input type="text" id="tangent-point" value="1" placeholder="例如: 0, 1.5, pi/2">
                    </div>
                </div>
                
                <div class="function-inputs" id="conic-inputs">
                    <div class="form-group">
                        <label for="conic-type">圆锥曲线类型</label>
                        <select id="conic-type">
                            <option value="ellipse">椭圆</option>
                            <option value="hyperbola">双曲线</option>
                            <option value="parabola">抛物线</option>
                            <option value="circle">圆</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="conic-params">参数 (a, b, h, k)</label>
                        <input type="text" id="conic-params" value="2, 1, 0, 0" placeholder="例如: 3, 2, 1, -1">
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="x-min">X 最小值</label>
                    <input type="number" id="x-min" value="-5">
                </div>
                
                <div class="form-group">
                    <label for="x-max">X 最大值</label>
                    <input type="number" id="x-max" value="5">
                </div>
                
                <div class="form-group">
                    <label for="y-min">Y 最小值</label>
                    <input type="number" id="y-min" value="-5">
                </div>
                
                <div class="form-group">
                    <label for="y-max">Y 最大值</label>
                    <input type="number" id="y-max" value="5">
                </div>
                
                <button id="plot-btn" class="btn">绘制图像</button>
                <button id="reset-btn" class="btn" style="background: linear-gradient(to right, #e74c3c, #c0392b);">重置设置</button>
                
                <div class="examples">
                    <h3>使用示例</h3>
                    <ul>
                        <li><strong>函数</strong>: sin(x), x^2, log(x)</li>
                        <li><strong>导函数</strong>: 输入原函数表达式</li>
                        <li><strong>切线</strong>: 输入函数和切点坐标</li>
                        <li><strong>椭圆</strong>: a=2, b=1, h=0, k=0</li>
                        <li><strong>双曲线</strong>: (x-h)^2/a^2 - (y-k)^2/b^2 = 1</li>
                        <li><strong>抛物线</strong>: (x-h)^2 = 4p(y-k)</li>
                    </ul>
                </div>
            </div>
            
            <div class="plot-area">
                <h2 class="section-title">函数图像</h2>
                <div id="plot"></div>
            </div>
        </div>
        
        <div class="footer">
            <p>© 2023 数学函数可视化工具 | 使用 function-plot.js 库 | 支持任意函数、导函数、切线和圆锥曲线的绘制</p>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 设置初始活动面板
            document.querySelectorAll('.function-type-btn').forEach(btn => {
                if (btn.classList.contains('active')) {
                    const type = btn.dataset.type;
                    document.getElementById(`${type}-inputs`).classList.add('active');
                }
            });
            
            // 函数类型切换
            document.querySelectorAll('.function-type-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    document.querySelectorAll('.function-type-btn').forEach(b => b.classList.remove('active'));
                    document.querySelectorAll('.function-inputs').forEach(input => input.classList.remove('active'));
                    
                    this.classList.add('active');
                    const type = this.dataset.type;
                    document.getElementById(`${type}-inputs`).classList.add('active');
                });
            });
            
            // 绘图按钮事件
            document.getElementById('plot-btn').addEventListener('click', plotFunction);
            
            // 重置按钮事件
            document.getElementById('reset-btn').addEventListener('click', function() {
                document.getElementById('function-expression').value = 'x^2';
                document.getElementById('derivative-expression').value = 'x^3 - 2*x';
                document.getElementById('tangent-function').value = 'sin(x)';
                document.getElementById('tangent-point').value = '1';
                document.getElementById('conic-params').value = '2, 1, 0, 0';
                document.getElementById('x-min').value = '-5';
                document.getElementById('x-max').value = '5';
                document.getElementById('y-min').value = '-5';
                document.getElementById('y-max').value = '5';
                
                plotFunction();
            });
            
            // 初始绘图
            plotFunction();
            
            function plotFunction() {
                const xMin = parseFloat(document.getElementById('x-min').value);
                const xMax = parseFloat(document.getElementById('x-max').value);
                const yMin = parseFloat(document.getElementById('y-min').value);
                const yMax = parseFloat(document.getElementById('y-max').value);
                
                const activeType = document.querySelector('.function-type-btn.active').dataset.type;
                let functions = [];
                
                try {
                    switch(activeType) {
                        case 'function':
                            const funcExpr = document.getElementById('function-expression').value;
                            functions = [
                                { fn: funcExpr }
                            ];
                            break;
                            
                        case 'derivative':
                            const derivFunc = document.getElementById('derivative-expression').value;
                            functions = [
                                { fn: derivFunc },
                                { fn: derivFunc, isDerivative: true }
                            ];
                            break;
                            
                        case 'tangent':
                            const tangentFunc = document.getElementById('tangent-function').value;
                            const point = parseFloat(document.getElementById('tangent-point').value);
                            functions = [
                                { fn: tangentFunc },
                                { fn: tangentFunc, isDerivative: true },
                                { fn: tangentFunc, tangentPoint: point }
                            ];
                            break;
                            
                        case 'conic':
                            const conicType = document.getElementById('conic-type').value;
                            const params = document.getElementById('conic-params').value.split(',').map(p => parseFloat(p.trim()));
                            functions = [
                                { conic: conicType, params: params }
                            ];
                            break;
                    }
                    
                    renderPlot(functions, xMin, xMax, yMin, yMax);
                } catch (error) {
                    alert(`绘图出错: ${error.message}`);
                    console.error(error);
                }
            }
            
            function renderPlot(functions, xMin, xMax, yMin, yMax) {
                const plotData = [];
                
                functions.forEach(funcObj => {
                    if (funcObj.fn) {
                        // 原函数
                        plotData.push({
                            fn: funcObj.fn,
                            graphType: 'polyline',
                            color: '#3498db'
                        });
                        
                        // 导函数
                        if (funcObj.isDerivative) {
                            // 使用数值方法计算导数，避免使用未定义的derivative函数
                            const derivativeExpr = getDerivativeExpression(funcObj.fn);
                            plotData.push({
                                fn: derivativeExpr,
                                graphType: 'polyline',
                                color: '#e74c3c'
                            });
                        }
                        
                        // 切线
                        if (funcObj.tangentPoint !== undefined) {
                            const tangentExpr = getTangentExpression(funcObj.fn, funcObj.tangentPoint);
                            plotData.push({
                                fn: tangentExpr,
                                graphType: 'polyline',
                                color: '#2ecc71'
                            });
                        }
                    } else if (funcObj.conic) {
                        // 圆锥曲线
                        const conicExpr = getConicExpression(funcObj.conic, funcObj.params);
                        plotData.push({
                            fn: conicExpr,
                            graphType: 'implicit',
                            color: '#9b59b6'
                        });
                    }
                });
                
                // 绘制图像
                try {
                    functionPlot({
                        target: '#plot',
                        width: document.getElementById('plot').offsetWidth,
                        height: 500,
                        xAxis: { domain: [xMin, xMax] },
                        yAxis: { domain: [yMin, yMax] },
                        grid: true,
                        data: plotData,
                        tip: {
                            xLine: true,
                            yLine: true,
                            renderer: function(x, y, index) {
                                return `(${x.toFixed(2)}, ${y.toFixed(2)})`;
                            }
                        }
                    });
                } catch (error) {
                    alert(`绘图出错: ${error.message}`);
                    console.error(error);
                }
            }
            
            // 使用数值方法计算导数表达式
            function getDerivativeExpression(func) {
                // 这里使用中心差分法计算导数
                // 注意：这是一个简化的实现，可能不适用于所有函数
                return `((${func.replace(/x/g, '(x+0.001)')}) - (${func.replace(/x/g, '(x-0.001)')})) / 0.002`;
            }
            
            function getTangentExpression(func, point) {
                // 数值方法计算导数
                const h = 0.0001;
                const f = functionPlot.$eval.builtIn({}, {}, 'x', func);
                const x = point;
                const dy = (f(x + h) - f(x - h)) / (2 * h);
                const y0 = f(x);
                
                return `${dy}*(x - ${x}) + ${y0}`;
            }
            
            function getConicExpression(type, params) {
                const [a, b, h, k] = params;
                
                switch(type) {
                    case 'ellipse':
                        return `(x-${h})^2/${a*a} + (y-${k})^2/${b*b} - 1`;
                    case 'hyperbola':
                        return `(x-${h})^2/${a*a} - (y-${k})^2/${b*b} - 1`;
                    case 'parabola':
                        return `(x-${h})^2 - 4*${a}*(y-${k})`;
                    case 'circle':
                        return `(x-${h})^2 + (y-${k})^2 - ${a*a}`;
                    default:
                        return `(x-${h})^2/${a*a} + (y-${k})^2/${b*b} - 1`;
                }
            }
        });
    </script>
</body>
</html>
    